﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using YShop.Application.Contracts.Shop.Inventorys;
using YShop.Core.Entites;
using YShop.Core.Managers.Caches;

namespace YShop.Application.Shop
{
    /// <summary>
    /// 库存服务
    /// </summary>
    [ApiDescriptionSettings("Shop")]
    public class InventoryService : IBaseService, IInventoryService
    {
        private readonly string LockCacheKey = "_Lock_Inventory";
        private Dictionary<string,decimal> LockCacheMapper => _cacheManager.GetOrCreate(LockCacheKey, _ => new Dictionary<string, decimal>());

        private readonly IRepository<Inventory> _repository;
        private readonly CacheManager _cacheManager;

        public InventoryService(IRepository<Inventory> repository,CacheManager cacheManager)
        {
            _repository = repository;
            _cacheManager = cacheManager;
        }

        /// <summary>
        /// 根据Sku获取库存
        /// </summary>
        /// <param name="skuId"></param>
        /// <returns></returns>
        public async Task<InventoryDto> GetBySkuIdAsync(string skuId)
        {
            var inventory = await _repository.FirstOrDefaultAsync(s => s.ProductDetailId == skuId);
            return inventory.Adapt<InventoryDto>();
        }


        /// <summary>
        /// 锁定库存
        /// </summary>
        public async Task LockAsync(string skuId,decimal quantity)
        {
            var currSku = await _repository.FirstOrDefaultAsync(s => s.ProductDetailId == skuId);
            if(currSku.Quantity - LockCacheMapper[skuId] < quantity)
            {
                Oops.Oh("库存不足！");
            }
            LockCacheMapper[skuId] += quantity;
            _cacheManager.Set(LockCacheKey, LockCacheMapper);
        }

        public async Task LockAsync(Dictionary<string, decimal> dictionaries)
        {
            foreach(var key in dictionaries.Keys)
            {
                var sku = await _repository.FirstOrDefaultAsync(s => s.ProductDetailId == key);
                if(sku.Quantity - LockCacheMapper[key] < dictionaries[key])
                {
                    Oops.Oh("库存不足！");
                }
            }

            // 锁定库存
            foreach(var key in dictionaries.Keys)
            {
                LockCacheMapper[key] += dictionaries[key];
            }
            _cacheManager.Set(LockCacheKey, LockCacheMapper);
        }
    }
}
